package com.astersoft.lib.util.mail;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;

public class ASEmailSenderThread implements Runnable {
    boolean runFlag = false;

    private ArrayList<ASEmail> list = null;
    private ASEmailSender sender = null;
    private Properties mailSettings;

    public ASEmailSenderThread(Properties mailServerSettings) {
        this.mailSettings = mailServerSettings;
        runFlag = true;
        list = new ArrayList<ASEmail>();
        sender = new ASEmailSender(mailSettings);
    }

    public boolean getRunFlag() {
        return runFlag;
    }

    public void kill() {
    	runFlag = false;
    }

    public void addEmail(ASEmail email) {
        list.add(email);
    }

    public void setRunFlag(boolean flag) {
        runFlag = flag;
    }

    public void run() {
        // set thread priority
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        ASEmail elem = null;
        // start email consuming
        for (Iterator<ASEmail> iter = list.iterator(); (iter.hasNext() && runFlag);) {

            // eat CPU here
            elem = iter.next();
            
            if (elem.attachments != null){
            	sender.send(elem.from, elem.to, elem.subject, elem.body, elem.htmlText);
            } else {
            	sender.send(elem.from, elem.to, "", "", "", elem.subject, elem.body, elem.attachments, elem.htmlText);
            }
            
            try {
                Thread.sleep(200);
            } catch (Exception e) {
            }
        }
    }
}
